package com.hotacorp.opencloud.common.resourcecommon.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

/**
 * 普通异常返回处理，当有异常时调用此控制器
 * @author lwg
 *
 */
@Controller
public class CustomErrorController extends BasicErrorController {
	public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", status.value());
		Map<String, Object> ddd = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
		String errorstr = (String)ddd.get("error");
		String pathstr = (String)ddd.get("path");
		StringBuilder sb = new StringBuilder();
		if (pathstr != null && pathstr.length() > 0) sb.append(pathstr);
		if (errorstr != null && errorstr.length() > 0) {
			if (sb.length() > 0) sb.append(" ");
			sb.append(errorstr);
		}
		if (sb.length() == 0) {
			sb.append(status.getReasonPhrase());
		}
        map.put("msg", sb.toString());
        map.put("data", "");
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
    }

}
